﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using UFSoft.UBF.Util.Log;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using UFIDA.U9.Base.Profile.Proxy;
using UFIDA.U9.Base.Profile;
using System.Xml.Linq;
using System.Xml;
using UFSoft.UBF.PL.Engine;
using System.Threading.Tasks;

namespace UFIDA.U9.Cust.XH.PlugBE.Tool
{
    public class PubWebClass
    {
        private static ILogger logger = LoggerManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        /// <summary>
        /// 当前日期后的所有单子开始同步
        /// </summary>
        public static DateTime startSysDate = Convert.ToDateTime("2024-12-08");
        #region 羲禾调用OA 接口事件

        public static OADepResult SaveDept(string postString, string userId = "")
        {
            OADepResult oARequestResult = null;
            try
            {

                string billtype = string.Format("同步部门");
                Log(string.Format("{0},报文：{1}", billtype, postString));
                string url = OAUrlHelper.getDepUrl;
                string context = PostHttpResponseRecord(billtype, url, postString, userId);
                try
                {
                    //解析返回报文
                    oARequestResult = JsonConvert.DeserializeObject<OADepResult>(context);
                }
                catch (Exception ex)
                {
                    throw new Exception(string.Format("{0}返回报文解析失败！返回报文：{1}", billtype, context));
                }
                if (oARequestResult.code.ToLower() != "1")
                {
                    //返回数据成功
                    throw new Exception(string.Format("{0}失败！返回报文：{1}", billtype, context));
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
            return oARequestResult;
        }

        public static string PostHttpResponseRecord(string billtype, string url, string postDataStr, string userId)
        {
            Log(string.Format("类型：{0}; 提交的地址：{1};提交的报文：{2}", billtype, url, postDataStr));
            Encoding encoding = Encoding.GetEncoding("utf-8");  //字符编码   
            HttpWebRequest request = null;
            //HTTPSQ请求  
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            request = WebRequest.Create(url) as HttpWebRequest;
            request.ProtocolVersion = HttpVersion.Version10;  //Http版本
            request.Method = "Post";   //请求方式
            request.ContentType = "application/json";
            //超时时间为5分钟
            request.Timeout = 5 * 60 * 1000;
            request.UserAgent = DefaultUserAgent;
            //如果需要POST数据     

            byte[] data = encoding.GetBytes(postDataStr.ToString());
            try
            {
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                Stream resStream = response.GetResponseStream();   //获取响应的字符串流  
                StreamReader sr = new StreamReader(resStream); //创建一个stream读取流  
                string content = sr.ReadToEnd();   //从头读到尾，放到字符串html 
                Log(string.Format("类型：{0}; 返回报文：{1} ", billtype, content));
                return content;
            }
            catch (Exception ex)
            {
                string errorMsg = string.Format("与OA通讯异常：{0}；提交的地址：{1}", ex.Message, url);
                Log(string.Format("类型：{0};{1} ", billtype, errorMsg));
                throw new Exception(errorMsg);
            }


        }


        #endregion



        #region  调用OAAPI


        /// <summary>
        /// 档案同步接口
        /// </summary>
        /// <param name="billtype"></param>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string RecordHttp(string billtype, string url, dynamic obj)
        {
            try
            {
                OAModel m = new OAModel();
                m.data = obj;
                string sysid = OAUrlHelper.Systemid;
                string date = DateTime.Now.ToString("yyyyMMddHHmmss");
                string md5 = OAUrlHelper.GetMd5Hash(sysid + OAUrlHelper.D_Password + date);
                m.header = new
                {
                    systemid = sysid,
                    currentDateTime = date,
                    Md5 = md5
                };
                string postDataStr = $"datajson={JsonConvert.SerializeObject(m)}";
                Log(string.Format("同步档案类型：{0}; 提交的地址：{1};提交的报文：{2}", billtype, url, postDataStr));
                Encoding encoding = Encoding.GetEncoding("utf-8");
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.Method = "Post";
                request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
                byte[] data = encoding.GetBytes(postDataStr);
                try
                {
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                    HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                    Stream resStream = response.GetResponseStream();
                    StreamReader sr = new StreamReader(resStream); //创建一个stream读取流  
                    string content = sr.ReadToEnd();   //从头读到尾，放到字符串html 
                    Log(string.Format("类型：{0}; 返回报文：{1} ", billtype, content));
                    return content;
                }
                catch (Exception ex)
                {

                    return "异常信息：" + ex.Message;
                }
            }
            catch (Exception e)
            {
                Log(string.Format("类型：{0}; 错误：{1} ", billtype, e.Message));
                return "异常信息：" + e.Message;
            }


        }


        /// <summary>
        /// 查询OA档案接口
        /// </summary>
        /// <param name="billtype"></param>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string FindHttp(string billtype, string url, string userid, dynamic maintable)
        {
            try
            {
                //OAModel m = new OAModel();
                //m.data = obj;
                string sysid = OAUrlHelper.Systemid;
                string date = DateTime.Now.ToString("yyyyMMddHHmmss");
                string md5 = OAUrlHelper.GetMd5Hash(sysid + OAUrlHelper.D_Password + date);
                dynamic obj = new
                {
                    operationinfo = new { @operator = userid },
                    mainTable = maintable,
                    header = new
                    {
                        systemid = sysid,
                        currentDateTime = date,
                        Md5 = md5
                    }
                };

                string postDataStr = $"datajson={JsonConvert.SerializeObject(obj)}";
                Log(string.Format("查询档案类型：{0}; 提交的地址：{1};提交的报文：{2}", billtype, url, postDataStr));
                Encoding encoding = Encoding.GetEncoding("utf-8");
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.Method = "Post";
                request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
                byte[] data = encoding.GetBytes(postDataStr);
                try
                {
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                    HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                    Stream resStream = response.GetResponseStream();
                    StreamReader sr = new StreamReader(resStream); //创建一个stream读取流  
                    string content = sr.ReadToEnd();   //从头读到尾，放到字符串html 
                    Log(string.Format("类型：{0}; 返回报文：{1} ", billtype, content));
                    //{"result":"{\"mainTable\":{\"id\":\"1\"}}"}

                    OAFindRes res = JsonConvert.DeserializeObject<OAFindRes>(content);
                    OAFindResResult result = JsonConvert.DeserializeObject<OAFindResResult>(res.result);

                    return result.mainTable.id ?? "";
                }
                catch (Exception e)
                {
                    Log(string.Format("类型：{0}; 错误：{1} ", billtype, e.Message));
                    return "";
                }
            }
            catch (Exception e)
            {
                Log(string.Format("类型：{0}; 错误：{1} ", billtype, e.Message));
                return "";
            }


        }

        /// <summary>
        /// 通过人员编码获取OA人员ID
        /// </summary>
        /// <param name="userCode"></param>
        /// <returns></returns>
        public static string GetOAUserIDByCode(string userCode)
        {
            if (string.IsNullOrEmpty(userCode))
            {
                return "";
            }
            UserData oAUser = GetOAUserInfo(userCode);
            if (oAUser.data != null)
            {
                if (oAUser.data.dataList.Count > 0)
                {
                    return oAUser.data.dataList[0].id;
                }
            }
            return "";
        }

        /// <summary>
        /// 获取OA人员信息
        /// </summary>
        /// <param name="userCode"></param>
        /// <returns></returns>
        public static UserData GetOAUserInfo(string userCode)
        {
            UserData oAUser = new UserData();
            try
            {
                string billtype = "获取OA人员信息";
                OAUserDto oAUserDto = new OAUserDto();
                oAUserDto.@params = new Params();
                oAUserDto.@params.workcode = userCode;
                oAUserDto.@params.base_custom_data = "id,subcompanyid1,departmentid";
                string url = OAUrlHelper.getHrmUserInfoWithPage;
                string json = JsonConvert.SerializeObject(oAUserDto);
                string context = CreatePostHttpResponse(billtype, url, json, "");
                try
                {
                    //解析返回报文
                    oAUser = JsonConvert.DeserializeObject<UserData>(context);
                }
                catch (Exception ex)
                {
                    Log(string.Format("获取OA人员信息返回报文解析失败！返回报文：{0}", context));
                }
                if (oAUser.code == "1")
                {
                    if (oAUser.data.dataList.Count == 0)
                    {
                        Log(string.Format("获取OA人员信息失败！未查询到人员编码为：{0} 的信息。当前返回数据行数为0！", userCode));
                    }
                    //返回数据成功
                    return oAUser;
                }
                else
                {
                    Log(string.Format("获取OA人员信息失败！返回报文：{0}", context));
                }
            }
            catch (Exception ex)
            {
                Log(string.Format("获取OA人员信息异常！返回报文：{0}", ex.Message));
            }

            return oAUser;

        }


        /// <summary>
        /// 通过部门编码获取OA部门ID
        /// </summary>
        /// <param name="userCode"></param>
        /// <returns></returns>
        public static string GetOADepIDByCode(string code)
        {
            if (string.IsNullOrEmpty(code))
            {
                return "";
            }
            UserData oAUser = GetOADepInfo(code);
            if (oAUser.data != null)
            {
                if (oAUser.data.dataList.Count > 0)
                {
                    return oAUser.data.dataList[0].id;
                }
            }
            return "";
        }
        /// <summary>
        /// 获取OA部门信息
        /// </summary>
        /// <param name="userCode"></param>
        /// <returns></returns>
        public static UserData GetOADepInfo(string depCode)
        {
            UserData oAUser = new UserData();
            try
            {
                string billtype = "获取OA部门信息";
                OADepDto oADto = new OADepDto();
                oADto.@params = new DepParams();
                oADto.@params.departmentcode = depCode;
                oADto.@params.base_custom_data = "id";
                string url = OAUrlHelper.findHrmdepartmentWithPage;
                string json = JsonConvert.SerializeObject(oADto);
                string context = CreatePostHttpResponse(billtype, url, json, "");
                try
                {
                    //解析返回报文
                    oAUser = JsonConvert.DeserializeObject<UserData>(context);
                }
                catch (Exception ex)
                {
                    Log(string.Format("获取OA部门信息返回报文解析失败！返回报文：{0}", context));
                }
                if (oAUser.code == "1")
                {
                    if (oAUser.data.dataList.Count == 0)
                    {
                        Log(string.Format("获取OA部门信息失败！未查询到部门编码为：{0} 的信息。当前返回数据行数为0！", depCode));
                    }
                    //返回数据成功
                    return oAUser;
                }
                else
                {
                    Log(string.Format("获取OA部门信息失败！返回报文：{0}", context));
                }
            }
            catch (Exception ex)
            {
                Log(string.Format("获取OA部门信息异常！返回报文：{0}", ex.Message));
            }

            return oAUser;

        }


        /// <summary>
        /// 通过分部编码获取OA分部ID
        /// </summary>
        /// <param name="userCode"></param>
        /// <returns></returns>
        public static string GetOAOrgIDByCode(string code)
        {
            if (string.IsNullOrEmpty(code))
            {
                return "";
            }
            UserData oAUser = GetOAOrgInfo(code);
            if (oAUser.data != null)
            {
                if (oAUser.data.dataList.Count > 0)
                {
                    return oAUser.data.dataList[0].id;
                }
            }
            return "";
        }
        /// <summary>
        /// 获取OA分部信息
        /// </summary>
        /// <param name="userCode"></param>
        /// <returns></returns>
        public static UserData GetOAOrgInfo(string Code)
        {
            UserData oAUser = new UserData();
            try
            {
                string billtype = "获取OA分部信息";
                OAOrgDto oADto = new OAOrgDto();
                oADto.@params = new OrgParams();
                oADto.@params.subcompanycode = Code;
                string url = OAUrlHelper.findHrmsubcompanyWithPage;
                string json = JsonConvert.SerializeObject(oADto);
                string context = CreatePostHttpResponse(billtype, url, json, "");
                try
                {
                    //解析返回报文
                    oAUser = JsonConvert.DeserializeObject<UserData>(context);
                }
                catch (Exception ex)
                {
                    Log(string.Format("获取OA分部信息返回报文解析失败！返回报文：{0}", context));
                }
                if (oAUser.code == "1")
                {
                    if (oAUser.data.dataList.Count == 0)
                    {
                        Log(string.Format("获取OA分部信息失败！未查询到分部编码为：{0} 的信息。当前返回数据行数为0！", Code));
                    }
                    //返回数据成功
                    return oAUser;
                }
                else
                {
                    Log(string.Format("获取OA分部信息失败！返回报文：{0}", context));
                }
            }
            catch (Exception ex)
            {
                Log(string.Format("获取OA分部信息异常！返回报文：{0}", ex.Message));
            }

            return oAUser;

        }




        #endregion



        #region 芯安OA对接参数

        /// <summary>
        /// 是否同步OA
        /// </summary>
        /// <returns></returns>
        public static bool IsSyncToOA()
        {

            //获取当前登录组织
            //var currentContext = UFSoft.UBF.Util.Context.ThreadContext.CurrentContext;
            //string orgcode = currentContext["OrgCode"] == null ? "" : currentContext["OrgCode"].ToString();//当前组织	
            string ProfileCode = "XAN_IsSyncOA";
            GetProfileValueProxy bpObj = new GetProfileValueProxy();
            bpObj.ProfileCode = ProfileCode;
            PVDTOData pVTDOData = bpObj.Do();
            bool isSync = false;
            if (pVTDOData == null || pVTDOData.ProfileValue == null)
            {
                return isSync;
            }
            isSync = (pVTDOData.ProfileValue == "1" || pVTDOData.ProfileValue.ToUpper() == "TRUE") ? true : false;
            return isSync;

        }
        /// <summary>
        /// OA的APPID
        /// </summary>
        /// <returns></returns>
        private static string GetOAAPPID()
        {
            string ProfileCode = "XAN_OAAPPID";
            GetProfileValueProxy bpObj = new GetProfileValueProxy();
            bpObj.ProfileCode = ProfileCode;
            PVDTOData pVTDOData = bpObj.Do();

            string ProfileValue = pVTDOData.ProfileValue;
            if (ProfileValue == "")
                throw new Exception("基础设置中未配置OA的APPID");
            return ProfileValue;
        }
        /// <summary>
        /// OA的CPK参数
        /// </summary>
        /// <returns></returns>
        private static string GetOACPK()
        {
            string ProfileCode = "XAN_OACPK";
            GetProfileValueProxy bpObj = new GetProfileValueProxy();
            bpObj.ProfileCode = ProfileCode;
            PVDTOData pVTDOData = bpObj.Do();

            string ProfileValue = pVTDOData.ProfileValue;
            if (ProfileValue == "")
                throw new Exception("基础设置中未配置OA的CPK");
            return ProfileValue;
        }

        /// <summary>
        /// 获取AccessToken
        /// </summary>
        /// <returns></returns>
        public static AccessToken GetAccessToken()
        {
            //检查缓存是否过期
            if (UFSoft.UBF.Util.Context.ThreadContext.CurrentContext["AccessToken"] != null)
            {

                var acToken = (AccessToken)UFSoft.UBF.Util.Context.ThreadContext.CurrentContext["AccessToken"];// HttpContext.Current.Application[" AccessToken"];
                if (acToken.expires_in > DateTime.Now)
                { //如果accesstoken 还未过期直接返回accesstoken
                    return acToken;
                }
            }
            AccessToken accessToken = new AccessToken();
            //string postStr = "";
            //string accessTokenUrl = GetAccessTokenUrl();
            try
            {
                //先获取许可注册码

                ResultData registAuthResultData = GetRegistAuth();
                //string content = "";// GetToken(accessTokenUrl, postStr);
                //先将java的rsa公钥转换为.net的格式
                string netSPK = RSAConvert.RSAPublicKeyJava2DotNet(registAuthResultData.spk);
                //然后使用.net格式公钥 加密secrit
                string rsaSecret = RSAConvert.RSAEncrypt(netSPK, registAuthResultData.secrit);
                //调用接口获取token
                ResultData resultData = GetToken(rsaSecret);
                accessToken.secrit = resultData.secrit;
                accessToken.spk = registAuthResultData.spk;
                accessToken.netspk = netSPK;
                accessToken.access_token = resultData.token;
                accessToken.rsaSecret = rsaSecret;//加密后的秘钥
                SaveAccessToken(accessToken);//缓存AccessToken
                //返回AccessToken
                return accessToken;

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);

            }

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="rsaSecret">加密后的Secret</param>
        /// <returns></returns>
        private static ResultData GetToken(string rsaSecret)
        {
            try
            {
                CookieContainer cc = new CookieContainer();
                //  cc.Add(new System.Uri(url), new Cookie("accessToken", tkn));
                HttpWebResponse response = GetTokenHttpResponse(rsaSecret);
                Stream stream = response.GetResponseStream();   //获取响应的字符串流  
                StreamReader sr = new StreamReader(stream); //创建一个stream读取流  
                string content = sr.ReadToEnd();   //从头读到尾，放到字符串html 
                Log(string.Format("请求token返回信息：{0}", content));
                ResultData resultData = JsonConvert.DeserializeObject<ResultData>(content);
                if (resultData.code != "0")
                {
                    throw new Exception(string.Format("请求token失败！返回信息：{0}", content));
                }
                return resultData;
            }
            catch (Exception ex)
            {

                throw new Exception(string.Format("请求token失败！" + ex.Message));
            }


        }
        /// <summary>
        /// /缓存AccessToken
        /// </summary>
        /// <param name="accessToken"></param>
        private static void SaveAccessToken(AccessToken accessToken)
        {
            //token过期时间
            accessToken.expires_in = DateTime.Now.AddMinutes(25);
            UFSoft.UBF.Util.Context.ThreadContext.CurrentContext.Add("AccessToken", accessToken);

        }

        /// <summary>
        /// 许可证注册
        /// </summary>
        private static ResultData GetRegistAuth()
        {

            try
            {
                CookieContainer cc = new CookieContainer();
                //  cc.Add(new System.Uri(url), new Cookie("accessToken", tkn));
                HttpWebResponse response = GetRegistAuthHttpResponse(OAUrlHelper.registUrl, "");
                Stream stream = response.GetResponseStream();   //获取响应的字符串流  
                StreamReader sr = new StreamReader(stream); //创建一个stream读取流  
                string content = sr.ReadToEnd();   //从头读到尾，放到字符串html 
                Log(string.Format("请求许可证返回信息：{0}", content));
                ResultData resultData = JsonConvert.DeserializeObject<ResultData>(content);
                if (resultData.code != "0")
                {
                    throw new Exception(string.Format("请求许可证失败！返回信息：{0}", content));
                }
                return resultData;
            }
            catch (Exception ex)
            {

                throw new Exception(string.Format("请求许可证失败！" + ex.Message));
            }


        }
        private static HttpWebResponse GetTokenHttpResponse(string rsaSecret)
        {
            string url = OAUrlHelper.applytoken;
            Log(string.Format("请求token提交的地址：{0} ;提交的报文：{1}", url, ""));
            Encoding encoding = Encoding.GetEncoding("utf-8");  //字符编码 
            HttpWebRequest request = null;
            //HTTPSQ请求  
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            request = WebRequest.Create(url) as HttpWebRequest;
            //if (cookie.Count == 0)
            //{
            //    request.CookieContainer = new CookieContainer();
            //    cookie = request.CookieContainer;
            //}
            //else
            //{
            //    request.CookieContainer = cookie;
            //}
            //身份认证
            //NetworkCredential nc = new NetworkCredential("bms100", "bms#12390","");
            //request.Credentials = nc;
            //request.PreAuthenticate = true;
            request.ProtocolVersion = HttpVersion.Version10;  //Http版本
            request.Method = "Post";   //请求方式
            request.ContentType = "application/json";
            string appId = GetOAAPPID();
            Log(string.Format("HttpHeader参数appId：{0}", appId));
            Log(string.Format("HttpHeader参数secret：{0}", rsaSecret));
            request.Headers.Add("appid", appId);
            request.Headers.Add("secret", rsaSecret);
            //request.Headers.Add("secret", registAuth);
            request.UserAgent = DefaultUserAgent;
            //如果需要POST数据     

            byte[] data = encoding.GetBytes("".ToString());
            try
            {
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }

                return request.GetResponse() as HttpWebResponse;

            }
            catch (Exception ex)
            {
                throw ex;
            }


        }

        private static HttpWebResponse GetRegistAuthHttpResponse(string url, string postDataStr)
        {
            Log(string.Format("许可证注册提交的地址：{0} ;提交的报文：{1}", url, postDataStr));
            Encoding encoding = Encoding.GetEncoding("utf-8");  //字符编码   
            HttpWebRequest request = null;
            //HTTPSQ请求  
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            request = WebRequest.Create(url) as HttpWebRequest;


            //if (cookie.Count == 0)
            //{
            //    request.CookieContainer = new CookieContainer();
            //    cookie = request.CookieContainer;
            //}
            //else
            //{
            //    request.CookieContainer = cookie;
            //}
            //身份认证
            //NetworkCredential nc = new NetworkCredential("bms100", "bms#12390","");
            //request.Credentials = nc;
            //request.PreAuthenticate = true;
            request.ProtocolVersion = HttpVersion.Version10;  //Http版本
            request.Method = "Post";   //请求方式
            request.ContentType = "application/json";
            request.Headers.Add("appid", GetOAAPPID());
            request.Headers.Add("cpk", GetOACPK());
            request.UserAgent = DefaultUserAgent;
            //如果需要POST数据     

            byte[] data = encoding.GetBytes(postDataStr.ToString());
            try
            {
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }

                return request.GetResponse() as HttpWebResponse;

            }
            catch (Exception ex)
            {
                throw ex;
            }


        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="postString">提交的内容</param>
        /// <param name="userId">流程创建人id（对应OA的人员ID）</param>
        public static OARequestResult doCreateRequest(dynamic postString, string userId, string strbilltype, string poststrnoe = "")
        {


            OARequestResult oARequestResult = null;
            try
            {

                string billtype = string.Format("创建{0}-OA流程", strbilltype);
                if (!string.IsNullOrEmpty(poststrnoe))
                {
                    Log(string.Format("{0},报文：{1}", billtype, poststrnoe));
                }
                else
                {
                    Log(string.Format("{0},报文：{1}", billtype, postString));
                }

                string url = OAUrlHelper.doCreateRequest;
                string context = CreatePostHttpResponse(billtype, url, postString, userId);
                try
                {
                    //解析返回报文
                    oARequestResult = JsonConvert.DeserializeObject<OARequestResult>(context);
                }
                catch (Exception ex)
                {
                    throw new Exception(string.Format("{0}返回报文解析失败！返回报文：{1}", billtype, context));
                }
                if (oARequestResult.code.ToLower() != "success")
                {
                    //返回数据成功
                    throw new Exception(string.Format("{0}失败！返回报文：{1}", billtype, context));
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
            return oARequestResult;
        }
        /// <summary>
        /// 提交流程
        /// </summary>
        /// <param name="postString">提交的内容</param>
        /// <param name="userId">流程创建人id（对应OA的人员ID）</param>
        public static OARequestResult submitRequest(string postString, string userId, string strbilltype, string poststr="")
        {
            OARequestResult oARequestResult = null;
            try
            {

                string billtype = string.Format("提交{0}-OA流程", strbilltype);

                if (!string.IsNullOrEmpty(poststr))
                {
                    Log(string.Format("{0},报文：{1}", billtype, poststr));
                }
                else
                {
                    Log(string.Format("{0},报文：{1}", billtype, postString));
                }
                string url = OAUrlHelper.submitRequest;
                string context = CreatePostHttpResponse(billtype, url, postString, userId);
                try
                {
                    //解析返回报文
                    oARequestResult = JsonConvert.DeserializeObject<OARequestResult>(context);
                }
                catch (Exception ex)
                {
                    throw new Exception(string.Format("{0}返回报文解析失败！返回报文：{1}", billtype, context));
                }
                if (oARequestResult.code.ToLower() != "success")
                {
                    //返回数据成功
                    throw new Exception(string.Format("{0}失败！返回报文：{1}", billtype, context));
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
            return oARequestResult;
        }


        public static string CreatePostHttpResponse(string billtype, string url, dynamic postDataStr, string userId)
        {
            Log(string.Format("类型：{0}; 提交的地址：{1};提交的报文：{2}", billtype, url, postDataStr));
            Encoding encoding = Encoding.GetEncoding("utf-8");  //字符编码   
            HttpWebRequest request = null;
            //HTTPSQ请求  
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            request = WebRequest.Create(url) as HttpWebRequest;
            request.ProtocolVersion = HttpVersion.Version10;  //Http版本
            request.Method = "Post";   //请求方式
            request.ContentType = "application/json";
            //超时时间为5分钟
            request.Timeout = 5 * 60 * 1000;
            //获取AccessToken
            AccessToken accessToken = GetAccessToken();
            #region 创建流程时需要以下参数
            if (!string.IsNullOrEmpty(userId))
            {
                //如果传入的userid不为空 则为创建流程
                request.Headers.Add("appId", GetOAAPPID());
                request.Headers.Add("token", accessToken.access_token);
                //加密userid
                string rsaUserId = RSAConvert.RSAEncrypt(accessToken.netspk, userId);
                request.Headers.Add("userid", rsaUserId);
                request.Headers.Add("secret", accessToken.rsaSecret);//加密后的秘钥
                request.ContentType = "application/x-www-form-urlencoded";

            }
            #endregion
            request.UserAgent = DefaultUserAgent;
            //如果需要POST数据     

            byte[] data = encoding.GetBytes(postDataStr.ToString());
            try
            {
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                Stream resStream = response.GetResponseStream();   //获取响应的字符串流  
                StreamReader sr = new StreamReader(resStream); //创建一个stream读取流  
                string content = sr.ReadToEnd();   //从头读到尾，放到字符串html 
                Log(string.Format("类型：{0}; 返回报文：{1} ", billtype, content));
                return content;
            }
            catch (Exception ex)
            {
                string errorMsg = string.Format("与OA通讯异常：{0}；提交的地址：{1}", ex.Message, url);
                Log(string.Format("类型：{0};{1} ", billtype, errorMsg));
                throw new Exception(errorMsg);
            }


        }



        //public static

        #endregion



        //*****************************************************************************//

        #region 判断参数

        /// <summary>
        /// 失败是否抛异常
        /// </summary>
        /// <returns></returns>
        public static bool IsThrowNew()
        {
            return true;
        }







        #endregion 判断参数END


        #region 所有公用类

        public static string Get(string urlString, Cookie cokie)
        {
            //定义局部变量
            HttpWebRequest httpWebRequest = null;
            HttpWebResponse httpWebRespones = null;
            Stream stream = null;
            string htmlString = string.Empty;

            //请求页面
            try
            {
                httpWebRequest = WebRequest.Create(urlString) as HttpWebRequest;

                //httpWebRequest.
            }
            //处理异常
            catch (Exception ex)
            {
                throw new Exception("建立页面请求时发生错误！", ex);
            }
            httpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; Maxthon 2.0)";
            //获取服务器的返回信息
            try
            {

                httpWebRespones = (HttpWebResponse)httpWebRequest.GetResponse();

                stream = httpWebRespones.GetResponseStream();
            }
            //处理异常
            catch (Exception ex)
            {
                throw new Exception("接受服务器返回页面时发生错误！", ex);
            }
            StreamReader streamReader = new StreamReader(stream, System.Text.Encoding.UTF8);
            //读取返回页面
            try
            {
                htmlString = streamReader.ReadToEnd();
            }
            //处理异常
            catch (Exception ex)
            {
                throw new Exception("读取页面数据时发生错误！", ex);
            }
            //释放资源返回结果
            streamReader.Close();
            stream.Close();
            return htmlString;
        }

        public static string ObjectToJson(object obj)
        {
            //Log(Newtonsoft.Json.JsonConvert.SerializeObject(obj));

            return JToken.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(obj)).ToString();
        }

        public static string JsonToObject(string json)
        {
            //try
            //{

            //    var result = JsonConvert.DeserializeObject<ResultData>(json);
            //    if (result.Response.head.ERRORCODE!="0")
            //    {

            //        return result.Response.List[0].syncmsg;
            //    }

            //}
            //catch (Exception ex)
            //{
            //    return string.Format("返回的报文：{0};{1}",json,ex.Message);
            //}
            return "";
            // JObject jObject = (JObject)JsonConvert.DeserializeObject(json);
            //JObject jObject = (JObject)jarray[1];
            //if (jObject["errcode"].ToString() != "0")
            //    return jObject["errmsg"].ToString();

        }

        public static long DateTimeToInt(DateTime datetime)
        {
            return (datetime.ToUniversalTime().Ticks - new DateTime(1970, 1, 1).Ticks) / 10000000;
        }

        /// <summary>
        /// 生成签名
        /// </summary>
        /// <param name="signature"></param>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <returns></returns>
        private static string GetSignature(string appSecret, string loginId, string timestamp, string nonce)
        {
            List<string> list = new List<string>();
            list.Add(appSecret);
            list.Add(timestamp);
            list.Add(nonce);
            list.Add(loginId);
            //默认排序
            list.Sort();
            string tmpStr = string.Join("", list.ToArray());
            return GetSHA1(tmpStr).ToLower();
        }

        public static string GetSHA1(string inputString)
        {
            SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
            byte[] encryptedBytes = sha1.ComputeHash(Encoding.ASCII.GetBytes(inputString));
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < encryptedBytes.Length; i++)
            {
                sb.AppendFormat("{0:x2}", encryptedBytes[i]);
            }
            return sb.ToString();
        }

        #region 同步通过GET方式发送数据
        /// <summary>
        /// 通过GET方式发送数据
        /// </summary>
        /// <param name="Url">url</param>
        /// <param name="postDataStr">GET数据</param>
        /// <param name="cookie">GET容器</param>
        /// <returns></returns>
        public static string SendDataByGET(string Url, string postDataStr, ref CookieContainer cookie)
        {
            string requestUriString = Url + (postDataStr == "" ? "" : "?") + postDataStr;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUriString);
            if (cookie.Count == 0)
            {
                request.CookieContainer = new CookieContainer();
                cookie = request.CookieContainer;
            }
            else
            {
                request.CookieContainer = cookie;
            }

            request.Method = "GET";
            //request.ContentType = "text/html;charset=UTF-8";
            request.ContentType = "text/json";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }


        #endregion


        #region 同步通过POST方式发送数据
        /// <summary>
        /// 通过POST方式发送数据
        /// </summary>
        /// <param name="Url">url</param>
        /// <param name="postDataStr">Post数据</param>
        /// <param name="cookie">Cookie容器</param>
        /// <returns></returns>
        public static string SendDataByPost(string Url, string postDataStr, ref CookieContainer cookie)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            if (cookie.Count == 0)
            {
                request.CookieContainer = new CookieContainer();
                cookie = request.CookieContainer;
            }
            else
            {
                request.CookieContainer = cookie;
            }

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = Encoding.GetEncoding("GB2312").GetBytes(postDataStr).Length;
            Stream myRequestStream = request.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
            myStreamWriter.Write(postDataStr);
            myStreamWriter.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();







            return retString;
        }

        /// <summary>
        /// 创建PostHttp请求
        /// </summary>
        /// <param name="url">Http请求地址</param>
        /// <param name="parameters">泛型集合</param>
        /// <param name="charset">字符编码</param>
        /// <returns></returns>



        private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受     
        }

        #endregion

        #region 写日志
        /// <summary>
        /// 写字符串日志
        /// </summary>
        /// <param name="msg">日志明细</param>
        public static void Log(string msg)
        {
            //ILogger logger = LoggerManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

            //logger.IsInfoEnabled;

            //if (logger.IsErrorEnabled)
            {
                logger.Error(msg);
            }
        }

        //public static void WriteLog(object msg)
        //{
        //    ILogger logger = null;
        //    string strType = "";
        //    string faultError = "";
        //    logger = LoggerManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        //    logger.Error(strType + "：成功\r\n" + result + "\r\n传输数据：-----------\r\n" + msg);
        //}

        /// <summary>
        /// 写对象日志
        /// </summary>
        /// <param name="msg">对象</param>
        public static void Log(string docType, string dataType, object msg, string result)
        {
            ILogger logger = null;
            string strType = "";
            string faultError = "";
            logger = LoggerManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
            //switch (type)
            //{
            //    case 0:
            //try
            //{
            strType = "同步到OA：" + docType + "---" + dataType;
            faultError = JsonToObject(result);

            if (faultError == "")//成功
            {
                string text = Newtonsoft.Json.JsonConvert.SerializeObject(msg);
                logger.Error(strType + "：成功\r\n" + result + "\r\n传输数据：-----------\r\n" + text);
                //logger.Error(Newtonsoft.Json.JsonConvert.SerializeObject(msg));
            }
            else
            {
                if (logger.IsErrorEnabled)
                {
                    string text = Newtonsoft.Json.JsonConvert.SerializeObject(msg);
                    logger.Error(strType + "：失败\r\n" + result + "\r\n传输数据：-----------\r\n" + text);
                    if (IsThrowNew())
                        throw new Exception(strType + "：" + faultError);
                }
            }
            //}
            //catch (Exception ex)
            //{

            //    throw ex;
            //}


        }

        /// <summary>
        /// 字段集合日志拼接
        /// </summary>
        /// <param name="properties">对象属性数组</param>
        /// <param name="dfData">集合对象</param>
        //public static void Log(System.Reflection.PropertyInfo[] properties, object dfData)
        //{
        //    StringBuilder strLogMsg = new StringBuilder();
        //    foreach (System.Reflection.PropertyInfo property in properties)
        //    {
        //        string pName = property.Name;
        //        object pValue = property.GetValue(dfData, null);
        //        strLogMsg.Append(string.Format("{0}:{1}\r\n", pName, pValue));
        //    }

        //    Log(strLogMsg);
        //}
        #endregion 写日志END
        #endregion

        //base64编码
        private static string Base64Enc(string content)
        {
            string strResult = Convert.ToBase64String(Encoding.UTF8.GetBytes(content));
            return strResult;

        }



    }
    public class JosnClas
    {

        public string errcode { get; set; }


        public string errmsg { get; set; }

        public string accessToken { get; set; }
    }
}
